<template>
    <div>
        <div class="authority-page">
            <!-- aside部分 -->
            <div class="manage-page-aside">
                <div class="head-section">
                    <div class="name" style="float: left; height:0.43rem;
                line-height:0.43rem">用户角色</div>
                    <div style="float: right">
                        <el-button
                                v-if="permission.add"
                                @click="handleAddRole"
                                type="primary"
                                plain
                        >新增
                        </el-button
                        >
                        <el-button
                                v-if="permission.modify"
                                @click="handleEditRole"
                                type="primary"
                                plain
                        >编辑
                        </el-button
                        >
                        <el-button
                                v-if="permission.delete"
                                @click="handleDelete"
                                type="primary"
                                plain
                        >删除
                        </el-button
                        >
                    </div>
                </div>
                <div class="role-table-section">
                    <el-scrollbar wrap-class="scrollbar-wrapper" style="height:100%">
                        <el-table
                                ref="refRoleTable"
                                :data="rolesTableData"
                                border
                                highlight-current-row
                                :row-class-name="tableRowClassName"
                                @row-click="handleCurrentChange"
                        >
                            <el-table-column type="index" label="序号" width="60">
                            </el-table-column>
                            <el-table-column
                                    prop="name"
                                    label="角色名称"
                                    style="cursor:pointer"
                            >
                            </el-table-column>
                            <el-table-column
                                    prop="remark"
                                    label="备注"
                                    style="cursor:pointer"
                            >
                            </el-table-column>
                        </el-table>
                    </el-scrollbar>
                </div>
            </div>

            <!-- content部分 -->
            <div class="authority-content manage-page-content">
                <!-- 包含的用户(这部分先隐藏) -->
                <!-- <div class="include-user">
                    <div style="margin-bottom:10px">
                        <el-button @click="handleAddRoleUser" type="primary" plain>添加</el-button>
                        <el-button @click="handleDeleteRoleUser" type="primary" plain>移除</el-button>
                    </div>
                    <el-table ref="singleTable" :data="userTableData" border highlight-current-row @current-change="handleCurrentChange">
                        <el-table-column type="index" label="序号" width="60"> </el-table-column>
                        <el-table-column prop="username" label="用户名" style="cursor:pointer"> </el-table-column>
                        <el-table-column prop="name" label="姓名" style="cursor:pointer"> </el-table-column>
                        <el-table-column prop="desc" label="状态" style="cursor:pointer"> </el-table-column>
                    </el-table>
                </div> -->

                <!-- 授权中心 -->
                <div class="diolog-group-table">
                    <div class="left">
                        <el-scrollbar
                                wrap-class="scrollbar-wrapper"
                                style="width:100%;height:100%"
                        >
                            <h4>已获得的权限：</h4>
                            <el-tree
                                    :data="manageGroupData"
                                    :indent="40"
                                    show-checkbox
                                    node-key="code"
                                    :props="defaultProps"
                                    @check="handleManageGroupSel"
                                    :default-expanded-keys="expandedManageKeys"
                                    @node-expand="clickManageExpend"
                                    @node-collapse="clickManageCollapse"
                            >
                            </el-tree>
                        </el-scrollbar>
                    </div>
                    <div class="dialog-group-btn">
                        <el-button
                                @click="dialogHandleGroupChange('add')"
                                :disabled="
								multipleAvailableGroupSel.length == 0 ||
									!permission.privilege_add
							"
                                size="small"
                                type="primary"
                                icon="el-icon-d-arrow-left"
                        >新 增
                        </el-button
                        >
                        <el-button
                                @click="dialogHandleGroupChange('delete')"
                                :disabled="
								multipleManageGroupSel.length == 0 ||
									!permission.privilege_delete
							"
                                size="small"
                                type="primary"
                        >移 除 <i class="el-icon-d-arrow-right"></i
                        ></el-button>
                    </div>
                    <div class="right">
                        <el-scrollbar
                                wrap-class="scrollbar-wrapper"
                                style="width:100%;height:100%"
                        >
                            <h4>可选权限：</h4>
                            <el-tree
                                    :data="availableGroupData"
                                    :indent="40"
                                    show-checkbox
                                    node-key="code"
                                    @check="handleAvailableGroupSel"
                                    :props="defaultProps"
                                    :default-expanded-keys="expandedAvailableKeys"
                                    @node-expand="clickAvailabeExpend"
                                    @node-collapse="clickAvailabeCollapse"
                            >
                            </el-tree>
                        </el-scrollbar>
                    </div>
                    <div style="margin-top:20px;text-align:right"></div>
                </div>
            </div>

            <!-- 新增角色弹框 -->
            <el-dialog
                    class="add-role-dia"
                    :title="isAddNew ? '新增角色' : '编辑角色'"
                    :visible.sync="dialogRoleVisible"
                    width="500px"
                    @close="resetForm"
                    :close-on-click-modal="false"
            >
                <el-form
                        :rules="rules"
                        :model="pojoRole"
                        ref="pojoForm"
                        label-width="100px"
                >
                    <el-form-item label="角色名称" prop="name">
                        <el-input v-model="pojoRole.name"></el-input>
                    </el-form-item>
                    <el-form-item label="备注" prop="remark">
                        <el-input v-model="pojoRole.remark"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button
                            v-if="isAddNew"
                            type="primary"
                            @click="addRoleSubmit('pojoForm')"
                    >确 定
                    </el-button
                    >
                    <el-button v-else type="primary" @click="editRoleSubmit('pojoForm')"
                    >确 定
                    </el-button
                    >
                    <el-button @click="dialogRoleVisible = false">取 消</el-button>
                </div>
            </el-dialog>

            <!-- 新增角色包含的用户弹框 -->
            <el-dialog
                    title="新增角色"
                    :visible.sync="dialogUserVisible"
                    width="500px"
                    @close="resetForm"
                    :close-on-click-modal="false"
            >
                <el-table
                        :data="dialogUserTableData"
                        border
                        style="margin-top:10px"
                        @selection-change="handleAvailableGroupSel"
                >
                    <el-table-column type="selection" width="55"></el-table-column>
                    <el-table-column type="index" label="序号" width="60">
                    </el-table-column>
                    <el-table-column prop="name" label="区域"></el-table-column>
                </el-table>
                <div slot="footer" class="dialog-footer">
                    <el-button
                            v-if="isAddNew"
                            type="primary"
                            @click="addRoleSubmit('pojoForm')"
                    >确 定
                    </el-button
                    >
                    <el-button v-else type="primary" @click="editRoleSubmit('pojoForm')"
                    >确 定
                    </el-button
                    >
                    <el-button @click="dialogRoleVisible = false">取 消</el-button>
                </div>
            </el-dialog>
        </div>
    </div>
</template>

<script>
    import ajax from '@/utils/ajax'
    import {deleteConfirm} from '@/utils/elementui.js'

    export default {
        data() {
            return {
                permission: {
                    get: true,
                    add: false,
                    modify: false,
                    delete: false,
                    privilege_add: false,
                    privilege_delete: false,
                    
                    // has_permission: false,
                    // available_permission: false,
                    // permission_add: false,
                    // permission_delete: false,
                },

                customerId: '',

                partnershipCodeId: null,
                roleId: null,
                rolesTableData: [],
                userTableData: [],
                // rolesTableData: [{ name: '管理员' }, { name: '技术人员' }, { name: '坐席' }, { name: '安保巡查人员' }],
                isAddNew: true,
                pojoRole: {
                    customerId: this.$store.getters.customerId,
                    name: '',
                    remark: '',
                },
                currentRole: null,
                dialogRoleVisible: false,
                dialogUserVisible: false,
                dialogUserTableData: [],
                // 权限
                manageGroupData: [],
                availableGroupData: [],
                multipleAvailableGroupSel: [],
                multipleManageGroupSel: [],

                rules: {
                    name: [
                        {required: true, message: '角色名称不能为空', trigger: 'blur'},
                    ],
                },

                tableIndex: 0,

                defaultProps: {
                    children: 'privilegeList',
                    label: 'title',
                },
                expandedManageKeys: [],
                expandedAvailableKeys: [],
            }
        },
        created() {
            this.customerId = this.$store.getters.customerId
            this.getRolesData()
        },
        mounted() {
            this.$store.dispatch('actions/dynamicTitleAction', this.$route.meta.title)
            this.setPermission()
        },
        methods: {
            // 设置可操作的权限
            setPermission() {
                // let route_permissions = this.$route.meta.sub_permissions
                let role_permissions = this.$store.getters.rolePermissions
                for (let item of role_permissions) {
                    if (item.action === '/web/privilege') {
                        for (let permission of item.privilegeList) {
                            switch (permission.action) {
                                case '/web/duty/query':
                                    this.permission.get = true
                                    break
                                case '/web/role/add':
                                    this.permission.modify = true
                                    break
                                case '/web/role/modify':
                                    this.permission.add = true
                                    break
                                case '/web/role/delete':
                                    this.permission.delete = true
                                    break
                                case '/web/privilege/add':
                                    this.permission.privilege_add = true
                                    break
                                case '/web/privilege/delete':
                                    this.permission.privilege_delete = true
                                    break
                                // 分配权限
                                // case '/web/duty/role':
                                //     this.permission.role_permission = true
                                //     for (let item of permission.permissions) {
                                //         switch (item.action) {
                                //             case '/web/duty/duty_permission/query':
                                //                 this.permission.has_permission = true
                                //                 break
                                //             case '/web/duty/all_permission/query':
                                //                 this.permission.available_permission = true
                                //                 break
                                //             case '/web/duty/duty_permission/add':
                                //                 this.permission.permission_add = true
                                //                 break
                                //             case '/web/duty/duty_permission/delete':
                                //                 this.permission.permission_delete = true
                                //                 break
                                //         }
                                //     }
                                //     break

                                default:
                                    break
                            }
                        }
                    }
                }
            },

            // 获取安保公司的角色
            getRolesData() {
                let po_customerId = this.customerId
                //console.log(po_partnershipCode)
                ajax.post({
                    url: this.$API.getSecurityRoles,
                    data: {customerId: po_customerId},
                    success: (response) => {
                        console.log(response)
                        let index = this.tableIndex
                        const resp = response.data.roleList
                        this.rolesTableData = resp
                        if (resp.length > 0) {
                            this.roleId = resp[index].id
                            this.getRoleAuthorityData()
                            // 默认选中table index行
                            this.$nextTick(() => {
                                this.$refs.refRoleTable.setCurrentRow(
                                    this.$refs.refRoleTable.data[index]
                                )
                                this.currentRole = resp[index]
                                this.roleId = resp[index].id
                            })
                        }
                    },
                    error: (res) => {
                        this.$message({
                            message: res.message,
                            type: 'error',
                        })
                    },
                })
            },

            // 获取角色已获得的权限和可选权限
            getRoleAuthorityData() {
                let po_id = this.roleId
                console.log(po_id)
                // 获取已获得的权限
                ajax.post({
                    url: this.$API.getRolePermission,
                    data: {id: po_id},
                    success: (response) => {
                        console.log(response)
                        const resp = response.data
                        this.manageGroupData = resp
                    },
                    error: (res) => {
                        //console.log(res)
                        this.$message({
                            message: res.message,
                            type: 'error',
                        })
                    },
                })
                // 获取可选取权限
                ajax.post({
                    url: this.$API.getAllPermission,
                    data: {id: po_id},
                    success: (response) => {
                        console.log(response)
                        const resp = response.data
                        this.availableGroupData = resp
                    },
                    error: (res) => {
                        //console.log(res)
                        this.$message({
                            message: res.message,
                            type: 'error',
                        })
                    },
                })
            },

            // 新增角色
            handleAddRole() {
                this.isAddNew = true
                this.dialogRoleVisible = true
            },
            // 提交新增角色
            addRoleSubmit(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.pojoRole.partnershipCode = this.partnershipCodeId
                        ajax.post({
                            url: this.$API.addSecurityRole,
                            data: this.pojoRole,
                            success: (response) => {
                                //console.log(response)
                                if (response.success) {
                                    this.getRolesData()
                                    this.dialogRoleVisible = false
                                    this.$message({
                                        message: response.message,
                                        type: 'success',
                                    })
                                }
                            },
                            error: (res) => {
                                //console.log(res)
                                this.$message({
                                    message: res.message,
                                    type: 'error',
                                })
                            },
                        })
                    } else {
                        //console.log('验证失败')
                    }
                })
            },

            // 编辑角色
            handleEditRole() {
                if (this.currentRole) {
                    this.isAddNew = false
                    let roleObj = this.currentRole
                    this.dialogRoleVisible = true
                    this.$nextTick(() => {
                        this.pojoRole.partnershipCode = this.partnershipCodeId
                        this.pojoRole.id = roleObj.id
                        this.pojoRole.name = roleObj.name
                        this.pojoRole.remark = roleObj.remark
                    })
                } else {
                    this.$message({
                        message: '请先选择要编辑的角色',
                        type: 'warning',
                    })
                }
            },
            // 提交编辑角色
            editRoleSubmit(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        //console.log(this.pojoRole)
                        ajax.post({
                            url: this.$API.modifySecurityRole,
                            data: this.pojoRole,
                            success: (response) => {
                                //console.log(response)
                                if (response.success) {
                                    this.getRolesData()
                                    this.dialogRoleVisible = false
                                    this.$message({
                                        message: response.message,
                                        type: 'success',
                                    })
                                }
                            },
                            error: (res) => {
                                //console.log(res)
                                this.$message({
                                    message: res.message,
                                    type: 'error',
                                })
                            },
                        })
                    } else {
                        //console.log('验证失败')
                    }
                })
            },
            // 删除
            handleDelete() {
                if (this.currentRole) {
                    let roleObj = this.currentRole
                    let po_id = roleObj.id
                    deleteConfirm(this).then((res) => {
                        if (res) {
                            //console.log(po_id)
                            ajax.post({
                                url: this.$API.deleteSecurityRole,
                                data: {ids: po_id},
                                success: (response) => {
                                    //console.log(response)
                                    if (response.success) {
                                        this.tableIndex = 0
                                        this.getRolesData()
                                        this.$message({
                                            message: response.message,
                                            type: 'success',
                                        })
                                    }
                                },
                                error: (response) => {
                                    this.$message({
                                        message: response.message,
                                        type: 'error',
                                    })
                                },
                            })
                        }
                    })
                } else {
                    this.$message({
                        message: '请先选择要删除的角色',
                        type: 'warning',
                    })
                }
            },

            // table每行加上index
            tableRowClassName({row, rowIndex}) {
                row.index = rowIndex
            },
            // 点击角色
            handleCurrentChange(row) {
                this.currentRole = row
                this.roleId = row.id
                this.tableIndex = row.index
                this.multipleManageGroupSel = []
                this.multipleAvailableGroupSel = []
                this.$nextTick(() => {
                    this.getRoleAuthorityData()
                })
            },

            // 新增角色包含的用户
            handleAddRoleUser() {
                this.dialogUserVisible = true
            },

            // 删除角色包含的用户
            handleDeleteRoleUser() {
            },

            // 选择管理的用户组
            handleManageGroupSel(nodeData, checkData) {
                this.multipleManageGroupSel = checkData.checkedNodes
            },
            // 勾选可选的用户组
            handleAvailableGroupSel(nodeData, checkData) {
                this.multipleAvailableGroupSel = checkData.checkedNodes
            },

            // 权限分配
            dialogHandleGroupChange(type) {
                let po_id = this.roleId
                let po_data = {}
                po_data.id = po_id
                let selectArr = []
                let po_url = ''
                if (type === 'add') {
                    // 新增
                    selectArr = this.multipleAvailableGroupSel
                    po_url = this.$API.addRolePermission
                } else {
                    // 移除
                    selectArr = this.multipleManageGroupSel
                    po_url = this.$API.deleteRolePermission
                }
                let permissionFormListArr = []
                for (let item of selectArr) {
                    permissionFormListArr.push(item.code)
                }
                po_data.ids = permissionFormListArr.join(',')

                ajax.post({
                    url: po_url,
                    data: po_data,
                    success: (response) => {
                        this.getRoleAuthorityData()
                        this.$message({
                            message: response.message,
                            type: 'success',
                        })
                        this.multipleAvailableGroupSel = []
                        this.multipleManageGroupSel = []
                    },
                    error: (res) => {
                        //console.log(res)
                        this.$message({
                            message: res.message,
                            type: 'error',
                        })
                    },
                })
            },

            // 已获得权限树节点打开
            clickManageExpend(nodeData) {
                //console.log(nodeData)
                if (this.expandedManageKeys.includes(nodeData.code)) {
                    return
                }
                this.expandedManageKeys.push(nodeData.code)
                //console.log(this.expandedManageKeys)
            },
            //已获得权限节点关闭
            clickManageCollapse(nodeData) {
                this.expandedManageKeys.splice(
                    this.expandedManageKeys.indexOf(nodeData.id),
                    1
                )
                //console.log(this.expandedManageKeys)
            },

            // 可选权限树节点打开
            clickAvailabeExpend(nodeData) {
                //console.log(nodeData)
                if (this.expandedAvailableKeys.includes(nodeData.code)) {
                    return
                }
                this.expandedAvailableKeys.push(nodeData.code)
                //console.log(this.expandedAvailableKeys)
            },
            //可选权限节点关闭
            clickAvailabeCollapse(nodeData) {
                this.expandedAvailableKeys.splice(
                    this.expandedAvailableKeys.indexOf(nodeData.id),
                    1
                )
                //console.log(this.expandedAvailableKeys)
            },

            // 重置表单
            resetForm() {
                this.$refs['pojoForm'].resetFields()
            },
        },
    }
</script>

<style lang="stylus" scoped>
    @import '~@/assets/styles/variables.styl'
>>>
    .authority-page
        position absolute
        top 0
        left 0
        right 0
        bottom 0
        padding 0.2rem
        overflow auto

        .role-table-section
            position absolute
            top 0.72rem
            left 0.2rem
            right 0.2rem
            bottom 0.4rem

        .authority-content
            .include-user
                min-height 4rem
                border-bottom 1px solid #16214d

            .diolog-group-table
                margin-top 0.2rem
                display: flex

                .dialog-group-btn
                    width 200px
                    padding: 0.2rem
                    box-sizing border-box

                    .el-button
                        display block
                        margin: 0.2rem auto

                .left, .right
                    width 360px
                    height 8.1rem
                    padding 10px
                    border 1px solid #fff
                    box-sizing border-box

            .dialog-area-head
                display: flex
                justify-content: space-between

    .el-table__body tr
        cursor pointer

    .el-table--striped .el-table__body tr.el-table__row--striped.current-row td, .el-table__body tr.current-row > td
        color: #fff
        background-color: rgba(68, 199, 244, 0.2) !important

    >>> .add-role-dia {
        .el-form .el-form-item:last-child {
            margin-bottom: 0
        }

        .el-dialog__footer {
            padding: 0 0.3rem 0.3rem
        }
    }
</style>
